package com.dawnClass.service.impl;


import com.dawnClass.VO.ArticleConsumerVO;
import com.dawnClass.mapper.ArticleMapper;
import com.dawnClass.mapper.ConsumerMapper;
import com.dawnClass.pojo.Article;
import com.dawnClass.pojo.ArticleExample;
import com.dawnClass.pojo.Consumer;
import com.dawnClass.service.ArticleService;
import com.dawnClass.util.ServiceResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private ConsumerMapper consumerMapper;



    @Override
    public ServiceResponse getArticle(String label) {
        ArticleExample articleExample = new ArticleExample();
        if (!label.equals("推荐")){
            articleExample.createCriteria().andArticleLabelEqualTo(label);
        }
        articleExample.setOrderByClause("article_datetime desc");
        List<Article> articleList = articleMapper.selectByExample(articleExample);
        List<ArticleConsumerVO> articleConsumerVOList = new ArrayList<>();
        for(Article article:articleList){
            Consumer consumer = consumerMapper.selectByPrimaryKey(article.getConsumerId());
            articleConsumerVOList.add(new ArticleConsumerVO(article,consumer));
        }

        if (articleList != null && articleList.size()>0)
            return ServiceResponse.getSuccess(articleConsumerVOList);
        return ServiceResponse.getFail(null);
    }


    /**
     * 获取文章详情
     * @param articleId
     * @return
     */
    @Override
    public ServiceResponse getArticleDetails(Integer articleId) {
        Article article = articleMapper.selectByPrimaryKey(articleId);
        if (article!=null){
            return ServiceResponse.getSuccess(article);
        }
        return ServiceResponse.getFail(null);
    }

    @Override
    public int saveArticle(String articleName, String articleContent, Date articleDatetime , Integer consumerId) {
        Article article = new Article();
        article.setConsumerId(consumerId);
        article.setArticleName(articleName);
        article.setArticleContent(articleContent.getBytes());
        article.setArticleDatetime(articleDatetime);
        article.setArticleFabulousNum(0);
        int row = articleMapper.insert(article);
        return row;
    }


}
